package com.fy56.platform.logistics.service.impl;

import com.alibaba.fastjson.JSON;
import com.fy56.platform.logistics.common.InterFaceResult;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.mapper.GmmsMemberOpenidRelateMapper;
import com.fy56.platform.logistics.mapper.GmmsMiniProgramMapper;
import com.fy56.platform.logistics.model.GmmsMiniProgram;
import com.fy56.platform.logistics.service.wx.IGmmsMiniProgramService;
import com.fy56.platform.logistics.utils.HttpClientUtils;
import com.fy56.platform.logistics.utils.ParamUtil;
import com.fy56.platform.logistics.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/*
 * @项目名称：
 * @类名称：GmmsCommonServiceImpl
 * @类描述：小程序获取WxService接口实现类
 * @创建人：
 * @作者单位：哈尔滨飞扬软件技术有限公司
 * --------------------------------------
 * @创建时间：2019-04-16 16:54:15
 * @version：1.0.0
 */
@Service
public class GmmsMiniProgramServiceImpl implements IGmmsMiniProgramService {

    @Autowired
    private GmmsMiniProgramMapper gmmsMiniProgramMapper;
    @Autowired
    private GmmsMemberOpenidRelateMapper gmmsMemberOpenidRelateMapper;


    @Override
    public ResultModel getOpenIdService(String code, String urlAddress, String companyId)throws  Exception {
        ResultModel resultModel = null;
        // 1 查询公司ID对应小程序信息，实现数据记录 小程序对应公司信息
        GmmsMiniProgram gmmsMiniProgram = gmmsMiniProgramMapper.getGmmsMiniProgramByContent(urlAddress, companyId, null);
        if(gmmsMiniProgram != null) {
            // 2 访问微信接口 获取openId信息
            String url = "https://api.weixin.qq.com/sns/jscode2session?js_code=" + code + "&appid=" + gmmsMiniProgram.getAppId() + "&secret=" + gmmsMiniProgram.getSecret() + "&grant_type=authorization_code";
            String resultContent = HttpClientUtils.postParameters(url, "");
            Map<String, Object> resMap = JSON.parseObject(resultContent);

            String openId = ParamUtil.getStringValue(resMap.get("openid"));
            String session_key = ParamUtil.getStringValue(resMap.get("session_key"));
            if (StringUtil.isNotEmpty(openId)) {
                Result resultObj = new Result(openId, session_key);
                // 1 设置返回配置小程序信息
                resultObj.setGmmsMiniProgram(gmmsMiniProgram);
                // 2 根据openId 查询仓配系统用户信息
                resultObj.setGmmsMember(getMemberByOpenId(gmmsMiniProgram.getUrlAddress(), openId));

                // 获取用户登录状态-若当前用户登录且没有执行退出，则表中会用当前openId记录信息
                /*GmmsMemberOpenidRelate gmmsMemberOpenidRelate = gmmsMemberOpenidRelateMapper.getGmmsMemberOpenidRelateByContent(openId, companyId);
                if(gmmsMemberOpenidRelate != null){
                    try{
                        // 根据openId 获取藏配接口用户信心
                        Map<String, Object> memberMap = getMemberByOpenId(gmmsMiniProgram.getUrlAddress(), openId);
                        resultObj.setGmmsMember(memberMap);
                    }catch (Exception ex){}
                }*/
                resultModel = new ResultModel(100, "获取小程序openId成功。" , resultObj);
            } else {
                resultModel = new ResultModel(101, "获取小程序openId失败：" + resultContent, null);
            }
        }else{
            resultModel = new ResultModel(101, "获取小程序openId信息失败：数据库中无当前地址对应的小程序配置信息。",null);
        }
        return  resultModel;
    }

    @Override
    public Object getMemberByOpenId(String url, String openId)throws Exception{
        Object resultObj = null;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tokenType","miniOpenId");
        param.put("token", openId);

        Map<String, String> postMap =  new HashMap<String, String>();
        postMap.put("param",JSON.toJSONString(param));
        String memberResult = HttpClientUtils.post(url + "ifs/userController_loginByToken_resultAction.action", postMap, null, 10000, 10000);
        // 解析获取用户信息
        // 2 判断返回值，解析并封装返回结果
        if(StringUtil.isNotEmpty(memberResult)){
            InterFaceResult interFaceResult = JSON.parseObject(memberResult).toJavaObject(InterFaceResult.class);
            resultObj = (interFaceResult != null) ? interFaceResult.getResultObject(): null;
        }
        /*if(StringUtil.isNotEmpty(memberResult)){
            Map<String,Object> memberResultMap = JSON.parseObject(memberResult);
            if(memberResultMap != null && !memberResultMap.isEmpty()){
                Integer resultCode = ParamUtil.getIntValue(memberResultMap.get("code"));
                Object resultState = memberResultMap.get("result");
                if((resultCode != null && resultCode ==100)){
                    if(memberResultMap.get("resultObject") != null){
                        resultMap = (Map) memberResultMap.get("resultObject");
                    }
                }
            }
        }*/
        return resultObj;
    }

    /**
     * 获取openId对象结果信息
     */
    private class Result{

        private String openid;                      // 获取当此openId
        private String session_key;                // 获取session_key信息
        private String appName;                     // 小程序名称
        private Long userId;
        private String loginName;
        private String tenantCode;

        /**
         * 小程序配置信息
         */
        private GmmsMiniProgram gmmsMiniProgram;
        /**
         * 用户信息
         */
        private Object gmmsMember;      //用户信息

        public Result(){
            super();
        }

        public Result(String openid, String session_key) {
            super();
            this.session_key = session_key;
            this.openid = openid;
        }

        public String getOpenid() {
            return openid;
        }

        public void setOpenid(String openid) {
            this.openid = openid;
        }

        public String getSession_key() {
            return session_key;
        }

        public void setSession_key(String session_key) {
            this.session_key = session_key;
        }

        public String getAppName() {
            return appName;
        }

        public void setAppName(String appName) {
            this.appName = appName;
        }

        public Long getUserId() {
            return userId;
        }

        public void setUserId(Long userId) {
            this.userId = userId;
        }

        public String getLoginName() {
            return loginName;
        }

        public void setLoginName(String loginName) {
            this.loginName = loginName;
        }

        public String getTenantCode() {
            return tenantCode;
        }

        public void setTenantCode(String tenantCode) {
            this.tenantCode = tenantCode;
        }

        public GmmsMiniProgram getGmmsMiniProgram() {
            return gmmsMiniProgram;
        }

        public void setGmmsMiniProgram(GmmsMiniProgram gmmsMiniProgram) {
            this.gmmsMiniProgram = gmmsMiniProgram;
        }

        public Object getGmmsMember() {
            return gmmsMember;
        }

        public void setGmmsMember(Object gmmsMember) {
            this.gmmsMember = gmmsMember;
        }

    }


}
